﻿using Entity;
using IRepository;
using IService;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace Service
{
    public class SysDictService : ISysDictService
    {
        private readonly ISysDictDataRepository _dictDataRepo;
        private readonly ISysDictTypeRepository _dictTypeRepo;
        private readonly IDistributedCache _redisCache; // 统一使用_redisCache作为变量名
        private const string _cachePrefix = "Dict:"; // 缓存键前缀

        public SysDictService(ISysDictTypeRepository dictTypeRepo,
                             ISysDictDataRepository dictDataRepo,
                             IDistributedCache redisCache)
        {
            _dictTypeRepo = dictTypeRepo;
            _dictDataRepo = dictDataRepo;
            _redisCache = redisCache; // 注入的缓存实例赋值给_redisCache
        }

        public async Task<List<SysDictData>> GetDictDatasByCodeAsync(string dictTypeCode)
        {
            string cacheKey = $"{_cachePrefix}{dictTypeCode}";

            // 从Redis读取缓存（使用_redisCache，而非_distributedCache）
            string cachedData = await _redisCache.GetStringAsync(cacheKey);
            if (!string.IsNullOrEmpty(cachedData))
            {
                return JsonSerializer.Deserialize<List<SysDictData>>(cachedData);
            }

            // 缓存未命中，查询数据库
            var dictDatas = await _dictDataRepo.GetDictDatasByTypeCodeAsync(dictTypeCode);
            if (dictDatas == null || !dictDatas.Any())
            {
                return new List<SysDictData>();
            }

            // 数据同步到Redis（使用_redisCache）
            var cacheOptions = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
            };
            await _redisCache.SetStringAsync(cacheKey, JsonSerializer.Serialize(dictDatas), cacheOptions);

            return dictDatas;
        }

        public async Task<string> GetDictLabelAsync(string dictTypeCode, string dictValue)
        {
            var dictDatas = await GetDictDatasByCodeAsync(dictTypeCode);
            var dictData = dictDatas.FirstOrDefault(d =>
                string.Equals(d.DictValue, dictValue, StringComparison.OrdinalIgnoreCase));
            return dictData?.DictLabel ?? string.Empty;
        }

        public async Task RefreshAllDictCacheAsync()
        {
            var allDictDatas = await _dictDataRepo.GetAllNormalDictDatasAsync();
            if (allDictDatas == null || !allDictDatas.Any())
            {
                return;
            }

            var groupedDatas = allDictDatas.GroupBy(d => d.DictTypeCode);
            foreach (var group in groupedDatas)
            {
                string cacheKey = $"{_cachePrefix}{group.Key}";
                var cacheOptions = new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
                };
                await _redisCache.SetStringAsync(cacheKey, JsonSerializer.Serialize(group.ToList()), cacheOptions);
            }
        }

        public async Task RefreshDictCacheByCodeAsync(string dictTypeCode)
        {
            var dictType = await _dictTypeRepo.GetDictTypeByCodeAsync(dictTypeCode);
            if (dictType == null)
            {
                throw new ArgumentException($"字典类型编码不存在：{dictTypeCode}");
            }

            var latesDatas = await _dictDataRepo.GetDictDatasByTypeCodeAsync(dictTypeCode);
            string cacheKey = $"{_cachePrefix}{dictTypeCode}";
            var cacheOptions = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
            };
            await _redisCache.SetStringAsync(cacheKey, JsonSerializer.Serialize(latesDatas), cacheOptions);
        }
    }
}
